#include<iostream>
#include<unistd.h>
#include<cassert>
#include<sys/bitypes.h>
#include<sys/wait.h>
#include<cstdlib>
#include<cstring>
#include<cstdio>


int main()
{
    //1 父进程打开一个管道文件
    int fd[2];
    int ret=pipe(fd);
    assert(ret==0);
    (void)ret;
    //创建子进程
    pid_t id=fork();
   
    //假设子进程接收数据
    if(id==0)
    {
        //接收方关闭写端
        close(fd[0]); //让紫禁城写
        //close(fd[1]);
        char buffer[64];
        int cnt=0;
        while(1)
        {
            sprintf(buffer,"this is parent process ! count: %d",cnt);;
            //int s= read(fd[0],buffer,sizeof(buffer)-1);
             write(fd[1],buffer,strlen(buffer));
            //if(s==0) //表示读取结束
               // break;
           // buffer[strlen(buffer)]='\0';
            //std::cout<<buffer<<std::endl;//打印接收到的信息
        
           // sleep(100);
        }
        std::cout<<"child process has exited"<<std::endl;
        close(fd[0]);
        exit(0);
    }

    //父进程发送数据
    //close(fd[0]);
    close(fd[1]);
   // int cnt=0;
    char buffer[1024];
   // while(cnt<10)
    while(1)
    {
      //  cnt++;
        //sprintf(buffer,"this is parent process ! count: %d",cnt);;
        //write(fd[1],buffer,strlen(buffer));
       // sleep(1);
       
        read(fd[0],buffer,sizeof buffer -1);
        buffer[strlen(buffer)]='\0';
        std:: cout<<buffer<<std::endl;
        break;
    }
    //close(fd[1]);
    close(fd[0]);
    //回收子进程僵尸
    int status=0;
    pid_t retid=waitpid(id,&status,0);
    std::cout<<"子进程退出信号:"<<(status&0x7F)<<std::endl;
    assert(retid==id);
    (void)retid;
    return 0;
}

